package com.lc.pianostudent.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.google.gson.GsonBuilder;

import com.lc.pianostudent.BaseApplication;
import com.lc.pianostudent.R;
import com.lc.pianostudent.conn.PostRegisterNext;
import com.lc.pianostudent.dialog.RegisterDialog;
import com.lc.pianostudent.dialog.ToastDialog;
import com.lc.pianostudent.fragment.MineFragment;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilApp;
import com.zcx.helper.util.UtilToast;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018/6/21.
 */

public class RegisterNextActivity extends BaseActivity implements View.OnClickListener{


    private int province_int= 0;
    private int city_int= 0;
    boolean isSpinnerFirst = true;
    private TimePickerView pvCustomTime;
    @BoundView(value = R.id.sex_layout,isClick = true) private RelativeLayout sex_layout;
    @BoundView(value = R.id.choose_born) private TextView choose_born;
    @BoundView(R.id.register_username) private EditText register_username;
    @BoundView(R.id.teacher_input) private EditText teacher_input;
    @BoundView(value = R.id.man_select,isClick = true) private ImageView man_select;
    @BoundView(value = R.id.women_select,isClick = true) private ImageView women_select;
    @BoundView(value = R.id.register,isClick = true) private LinearLayout register;
    @BoundView(value = R.id.rl_title_back, isClick = true)

    private Timer timer = null;//计时器
    private TimerTask timerTask = null;
    private int i = 3;
     private ToastDialog dialog;

    private String year = "",month = "";
    private int sex_int = 1;

    //注册接口
    public PostRegisterNext postRegisterNext = new PostRegisterNext(new AsyCallBack<PostRegisterNext.PostRegisterNextInfo>(){


        @Override
        public void onSuccess(String toast, int type, Object o, PostRegisterNext.PostRegisterNextInfo postRegisterNextInfo) throws Exception {
            super.onSuccess(toast, type, o, postRegisterNextInfo);
            BaseApplication.BasePreferences.setIsLogin(true);
            BaseApplication.BasePreferences.saveUID(postRegisterNextInfo.user_id);
            BaseApplication.BasePreferences.saveHeadImg(postRegisterNextInfo.avatar);
            BaseApplication.BasePreferences.setLoginPass(getIntent().getStringExtra("password"));
            BaseApplication.BasePreferences.savePhone(getIntent().getStringExtra("telephone"));
            BaseApplication.BasePreferences.saveName(postRegisterNextInfo.name);
            BaseApplication.BasePreferences.savePerson(postRegisterNextInfo.person);
            BaseApplication.BasePreferences.saveTeacherId(postRegisterNextInfo.teacherid);
            BaseApplication.BasePreferences.saveTeacherName(postRegisterNextInfo.teacher);

            startTime();
            dialog.show();


            try {
                ((MineFragment.CallBack)getAppCallBack(MineFragment.class)).onRefresh();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFail(final String toast, int type) throws Exception {

//            UtilToast.show(toast);
            new RegisterDialog(RegisterNextActivity.this,R.layout.dialog_register,toast){

                @Override
                public void confirm() {

                }

                @Override
                public void phone() {
                    UtilApp.call(toast);
                }
            }.show();
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_next);
        setBackTrue();

       initCustomTimePicker();
        initView();


    }


    private void initView() {
        setTitleName("下一步");
        BaseApplication.BasePreferences.saveChoose("2");
        dialog = new ToastDialog(this, R.layout.dialog_login_toast){

            @Override
            public void cancel() {
                this.dismiss();
            }

            @Override
            public void confirm() {
                //如果用户已经设置过支付密码，存起来，用于判断用户是否已经设置了支付密码
                //    BaseApplication.BasePreferences.saveIsPayPass(true);
                this.dismiss();
            }
        };

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sex_layout:
                Log.e("====jy7","----");
                    pvCustomTime.show(); //弹出自定义时间选择器

                break;


            case R.id.man_select:
                man_select.setImageResource(R.mipmap.register_sex_checked);
                women_select.setImageResource(R.mipmap.register_sex_default);
                sex_int = 1;
                break;

            case R.id.women_select:
                women_select.setImageResource(R.mipmap.register_sex_checked);
                man_select.setImageResource(R.mipmap.register_sex_default);
                sex_int = 0;
                break;

            case R.id.register:
                if (TextUtils.isEmpty(register_username.getText().toString().trim())) {
                    UtilToast.show("请输入真实姓名");
                } else if (choose_born.getText().toString().trim().equals("请选择")) {
                    UtilToast.show("请选择出生年月");
                } else if (TextUtils.isEmpty(teacher_input.getText().toString().trim())) {
                    UtilToast.show("请输入老师账号");
                }  else {

                    postRegisterNext.cname = register_username.getText().toString().trim();
                    postRegisterNext.confirm_password = getIntent().getStringExtra("password");
                    postRegisterNext.password = getIntent().getStringExtra("password");
                    postRegisterNext.username = getIntent().getStringExtra("telephone");
                    postRegisterNext.mouse =month;
                    postRegisterNext.year = year;
                    if(sex_int == 1){
                        postRegisterNext.sex = "1";
                    }else {
                        postRegisterNext.sex = "2";
                    }
                    postRegisterNext.type = "0";
                    postRegisterNext.teacher = teacher_input.getText().toString().trim();
                    postRegisterNext.execute();

                }
                break;

            case R.id.rl_title_back:
                if(BaseApplication.BasePreferences.getIsLogin()){
                    stopTime();
                    dialog.dismiss();
                    if (NavigationActivity.onClickProduct != null) {
                        NavigationActivity.onClickProduct.setOnClick();
                    }
                    finish();
                    BaseApplication.INSTANCE.finishActivity(RegisterActivity.class,LoginActivity.class);
                    startActivity(new Intent(RegisterNextActivity.this,VipActivity.class).putExtra("from","2"));
                }else {
                    finish();
                    BaseApplication.INSTANCE.finishActivity(RegisterActivity.class);
                }

                break;
        }
    }


    private void initCustomTimePicker() {

        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
//        Calendar selectedDate = Calendar.getInstance();//系统当前时间
//        Calendar startDate = Calendar.getInstance();
//        startDate.set(2014, 1, 23);
//        Calendar endDate = Calendar.getInstance();
//        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                choose_born.setText(getTime(date));
            }
        })
                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               .setDividerColor(Color.WHITE)//设置分割线的颜色
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)
               .gravity(Gravity.RIGHT)// default is center*/
//                .setDate(selectedDate)
//                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentSize(18)
                .setType(new boolean[]{true, true, false, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFFdedede)

                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .build();

    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat format2 = new SimpleDateFormat("MM");
        year = format1.format(date);
        month = format2.format(date);
        return format.format(date);
    }


    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {

            startTime();
//            Log.e("--i",i+"===jy");
            if(i==0){
                stopTime();
                dialog.dismiss();
                if (NavigationActivity.onClickProduct != null) {
                    NavigationActivity.onClickProduct.setOnClick();
                }

                finish();
                BaseApplication.INSTANCE.finishActivity(RegisterActivity.class,LoginActivity.class);
                startActivity(new Intent(RegisterNextActivity.this,VipActivity.class).putExtra("from","2"));
            }
        };
    };

    /**
     * 开始自动减时
     */
    private void startTime() {
        if(timer==null){
            timer = new Timer();
        }

        timerTask = new TimerTask() {

            @Override
            public void run() {
                i--;//自动减1
                Message message = Message.obtain();
                message.arg1=i;
                mHandler.sendMessage(message);//发送消息
            }
        };
        timer.schedule(timerTask, 1000);//1000ms执行一次
    }
    /**
     * 停止自动减时
     */
    private void stopTime() {
        if(timer!=null)
            timer.cancel();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        if(BaseApplication.BasePreferences.getIsLogin()){
            stopTime();
            dialog.dismiss();
            if (NavigationActivity.onClickProduct != null) {
                NavigationActivity.onClickProduct.setOnClick();
            }
            finish();
            BaseApplication.INSTANCE.finishActivity(RegisterActivity.class,LoginActivity.class);
            startActivity(new Intent(RegisterNextActivity.this,VipActivity.class).putExtra("from","2"));
        }else {
            finish();
            BaseApplication.INSTANCE.finishActivity(RegisterActivity.class);
        }

    }



}
